/*
* name: scroll-row
* version: v1.0
* update: 优化
* date:2014-04-15
*/
define(function(require, exports, module) {
   var $ = require('jquery');

	$.fn.scrollrow = function(config) {
		var opt = {
				up: ".arr_up",
				down: ".arr_down",
				wrap:'ul',
				cell:'li',
				line: 1,
				speed: 500,
				timer: 5e3,
				callback: function(nowRow){},
				ext: function(totalRow){}
			},
			$this = $(this),
			$wrap, $cell, nowRow = 1, _T, lasted, scrollUp, scrollDown, _btnUp, _btnDown;
			
		$.extend(opt, config || {}, $(this).data('config') || {});
		
		$wrap = $this.find(opt.wrap);
		$cell = $this.find(opt.cell);
		lineH = $cell.outerHeight(true),
		cols = Math.floor($this.width() / $cell.outerWidth()) ? Math.floor($this.width() / $cell.outerWidth()) : 1,
		rows = Math.floor($this.height() / lineH),
		rowsall = Math.ceil($cell.length / cols),
		line = opt.line > rows ? rows : opt.line,
		upHeight = 0 - line * lineH,
		totalRow = Math.ceil(rowsall / rows)
		_btnUp = $(opt.up);
		_btnDown = $(opt.down);
		
		if (rowsall * lineH <= $this.height()) {
			_btnUp.remove();
			_btnDown.remove();
			opt.ext && opt.ext(totalRow);
			console.log("scroll-row: lines no enough to scroll-row.");
			return $this
		};
		
		scrollUp = function() {
			$wrap.stop(1).animate({marginTop: upHeight}, opt.speed, function() {
				$wrap.css('marginTop', 0);
				for (i = 1; i <= line; i++) {
					$this.find(opt.cell + ":lt(" + cols + ")").appendTo($wrap)
				}
			});
			nowRow = (nowRow <= 1 ? totalRow : nowRow - 1);
			opt.callback && opt.callback(nowRow);
		};
		
		scrollDown = function() {
			lasted = $cell.length - cols - 1;
			for (i = 1; i <= line; i++) {
				$this.find(opt.cell + ":gt(" + lasted + ")").show().prependTo($wrap)
			};
			$wrap.stop(1).css('marginTop', upHeight).animate({marginTop: 0}, opt.speed);
			nowRow = (nowRow >= totalRow ? 1 : nowRow + 1);
			opt.callback && opt.callback(nowRow);
		};
		
		if (opt.timer) {
			_T = setInterval(function() {scrollUp()}, opt.timer);
			$this.hover(function() {
				clearInterval(_T)
			}, function() {
				_T = setInterval(function() {scrollUp()}, opt.timer)
			})
		};
		
		_btnUp.click(function() {
			scrollUp()
		})
		_btnDown.click(function() {
			scrollDown()
		});
		
		opt.ext && opt.ext(totalRow)
		
	};

})
